<template>
  <view style="padding: 10px;">
    <uni-forms ref="forms" :rules="rules" v-model="violationClassIntervalDetail">
      <uni-section title="违纪学生照片" type="line">
        <uni-forms-item :required="!isDetail">
          <view style="flex-direction: row;">
            <image-picker ref="imagePicker" :value.sync="violationClassIntervalDetail.images" :limit="9" @success="onSuccess" :readonly="isDetail" @change="onImageChange"/>
            <uni-view v-if="imageErrorShow">
              <uni-text class="rule-error-text"><span>请选择违纪学生照片</span></uni-text>
            </uni-view>
          </view>
        </uni-forms-item>
      </uni-section>
      <uni-section title="违纪类型" type="line" style="margin-top: 20rpx;" >
        <uni-forms-item name="violationType" :required="!isDetail">
          <dict-select :type="isDetail ? 'text' : 'radio'" ref="violationTypeNode" dict-type="class_interval_violation_type" v-model="violationClassIntervalDetail.violationType"/>
        </uni-forms-item>
      </uni-section>
      <uni-section title="违纪班级" type="line" style="margin-top: 20rpx;">
        <uni-forms-item name="classId" :required="!isDetail">
          <dict-select
              :type="isDetail ? 'text' : 'select'"
              ref="violationClassNode"
              :options="classOptions"
              id-key="value"
              name-key="text"
              v-model="violationClassIntervalDetail.classId"/>
        </uni-forms-item>
      </uni-section>
      <uni-section title="违纪情况说明" type="line">
        <uni-forms-item>
          <text v-if="isDetail" style="margin-left: 20rpx">{{ violationClassIntervalDetail.note || '无' }}</text>
          <uni-easyinput type="textarea" v-model="violationClassIntervalDetail.note" placeholder="请输入违纪情况" v-else />
        </uni-forms-item>
      </uni-section>
      <uni-section title="违纪处理结果" type="line" v-if="!notReceive">
        <uni-forms-item name="handleContent" :required="!isDetail">
          <text v-if="isDetail" style="margin-left: 20rpx">{{ violationClassIntervalDetail.handleContent || '无' }}</text>
          <uni-easyinput type="textarea" v-model="violationClassIntervalDetail.handleContent" placeholder="请输入违纪处理情况" v-else />
        </uni-forms-item>
      </uni-section>
      <uni-section title="违纪时间" type="line" style="margin-top: 20rpx">
        <uni-forms-item name="violationTime" :required="!isDetail">
          <text v-if="isDetail" style="margin-left: 20rpx">{{ violationClassIntervalDetail.violationTime }}</text>
          <uni-datetime-picker type="datetime" :clear-icon="false" :start="getTimestamp(-1,6,0)" :end="new Date().getTime()"
                               placeholder="选择请违纪时间" v-model="violationClassIntervalDetail.violationTime" v-else/>
        </uni-forms-item>
      </uni-section>
      <uni-section title="违纪学生" type="line" style="margin-top: 20rpx;" v-if="notEmpty(violationClassIntervalDetail.studentNameList)">
        <uni-list>
          <uni-list-item
              :title="item"
              v-for="(item,index) in violationClassIntervalDetail.studentNameList"
              :key="index">
            <template v-slot:footer>
              <uni-badge type="success" :text="violationClassIntervalDetail.className+'班'" size="normal" style="align-self: center;" :custom-style="{fontSize: '13px'}" />
            </template>
          </uni-list-item>
        </uni-list>
      </uni-section>
      <view style="display: flex;gap: 10rpx;margin-top: 20rpx;">
        <button type="primary" size="mini" style="flex: 1" @click="showSelectStudent" v-if="canReceive">认领</button>
        <button type="primary" size="mini" style="flex: 1" @click="openEdit" v-if="canEdit">编辑</button>
        <button type="primary" size="mini" style="flex: 1" @click="save(true)" v-if="canSubmit">提交</button>
        <button type="warn" size="mini" style="flex: 1" @click="del" v-if="canDel">删除</button>
        <button type="warn" size="mini" style="flex: 1" @click="cancel" v-if="canCancel">取消</button>
      </view>
    </uni-forms>
	
    <uni-popup ref="popups" background-color="#fff">
      <view class="popup-content">
        <scroll-view :scroll-y="true" style="height: 600rpx;margin-top: 10rpx;margin-bottom: 20rpx" @scrolltolower="loadMore">
          <uni-list>
            <uni-list-item
                v-for="item in queryStudentInfos"
                show-switch
                :thumb="item.stuPhoto"
                :title="item.studentName"
                :note="item.className"
                @switchChange="studentSwitchChange(item,$event)">
            </uni-list-item>
          </uni-list>
        </scroll-view>
        <uni-easyinput type="textarea" v-model="violationClassIntervalDetail.handleContent" placeholder="请输入违纪处理情况" />
        <button type="primary" style="margin-top: 20rpx" @click="receiveStudents">添加</button>
      </view>
    </uni-popup>

  </view>
</template>

<script>
import violationClassIntervalApi from "@/api/modules/violationClassInterval";
import {getTimestamp, setTitle} from "@/js/common";
import student from '@/api/modules/student';
import teacherClass from '@/api/modules/teachClass';
import DictSelect from "@/components/dict-select/index.vue";


export default {
  components: {DictSelect},
  data() {
    return {
      id: null,
      topName: null,
      manager: false,
      violationClassIntervalDetail: {},
      queryStudentInfoPage : 1,
      queryStudentInfoTotalPage : null,
      queryStudentInfoPageSize: 10,
      queryStudentInfos: [],
      classOptions:[],
      classId:null,
      imageErrorShow: false,
      rules: {
        handleContent: {
          "rules": [
            { required: true, errorMessage: '请输入违纪处理内容', trigger: 'blur' }
          ]
        },
        violationType: {
          "rules": [
            {required: true, errorMessage: '请选择违纪类型', trigger: 'change'}
          ]
        },
        classId: {
          "rules": [
            {required: true, errorMessage: '请选择违纪班级', trigger: 'change'}
          ]
        },
        violationTime: {
          "rules": [
              {required: true, errorMessage: '请选择违纪时间', trigger: 'change'}
          ]
        },
      },
    }
  },
  created(){
    this.manager = this.getStorage("roleName",'') === '部门经理';
    console.log("是否为部门经理",this.manager);
  },
  onLoad(option) {
    this.id = option.id;
    this.topName = this.id ? "课间违纪详情" : '新增课间违纪';
    this.getViolationClassIntervalDetail();
    if(this.isEmpty(this.classOptions)){
      this.getClassIdAndNames();
    }
  },
  watch: {
    topName(val){
      setTitle(val);
    }
  },
  computed: {
    isAdd(){
      return this.topName === '新增课间违纪';
    },
    isUpdate(){
      return this.topName === '修改课间违纪';
    },
    isDetail(){
      return this.topName === '课间违纪详情';
    },
    notReceive(){
      return this.isEmpty(this.violationClassIntervalDetail.studentIds);
    },
    canReceive(){
      // 是班主任, 且没有认领过，且是详情
      return !this.manager && this.notReceive && this.isDetail;
    },
    canEdit() {
      // 部门经理在详情页面可以删除
      return this.isDetail && this.manager;
    },
    canSubmit() {
      // 不是详情时
      return !this.isDetail;
    },
    canDel() {
      // 部门经理在详情页面可以删除
      return this.isDetail && this.manager;
    },
    canCancel() {
      // 不是详情就可取消
      return !this.isDetail;
    }
  },
  methods: {
    showSelectStudent(){
      if(this.isEmpty(this.queryStudentInfos)){
        this.getStudentList();
      }
      this.$refs.popups.open("center");
    },
    getTimestamp,
    onImageChange(imageFiles){
      this.imageErrorShow = imageFiles.length === 0;
      this.$set(this.violationClassIntervalDetail,"studentNum",imageFiles.length);
      console.log('onImageChange',this.violationClassIntervalDetail.studentNum);
    },
    onSuccess(){
      // 在编辑页面点提交
      let violationClassIntervalInfo = this.getSaveViolationClassIntervalInfo();
      if(violationClassIntervalInfo === null){
        this.toast('获取待操作信息失败',1000);
        return;
      }
      this.showLoadingBySubmit();
      violationClassIntervalApi.save(violationClassIntervalInfo).then(resp=>{
        this.hideLoading();
        if(resp.code === 200){
          this.toast('保存成功');
        }else {
          this.toast("保存失败");
        }
        this.goBack(500);
      }).catch(error=>{
        this.hideLoading();
        this.toast(this.getErrorResMsg(error));
      });
    },
    getSaveViolationClassIntervalInfo(){
      if(!this.violationClassIntervalDetail){
        return null;
      }
      return {
        id: this.violationClassIntervalDetail.id,
        images: this.violationClassIntervalDetail.images,
        studentNum: this.violationClassIntervalDetail.studentNum,
        note: this.violationClassIntervalDetail.note,
        handleContent: this.violationClassIntervalDetail.handleContent,
        violationTime: this.violationClassIntervalDetail.violationTime,
        classId: this.violationClassIntervalDetail.classId ? this.violationClassIntervalDetail.classId : null,
        studentIds: this.violationClassIntervalDetail.studentIds ? this.violationClassIntervalDetail.studentIds+'' : null,
        violationType: this.violationClassIntervalDetail.violationType
      };
    },
    openEdit(){
      this.topName = '修改课间违纪';
    },
    save(){
      // 编辑页面保存或提交
      let hasImageFile = this.$refs.imagePicker.hasImageFile();
      this.imageErrorShow = !hasImageFile;
      this.$refs.forms.validate(null,null).then(()=>{
        if(this.imageErrorShow){
          return;
        }
        this.$refs.imagePicker.uploadImages();
      }).catch(err=>{
        console.log("保存提交时参数校验不通过",err);
      });
    },

    del(){
      violationClassIntervalApi.delete(this.id).then(resp=>{
        this.handleRes(resp).then(()=>{
          this.toast("删除成功");
          this.goBack(500);
        });
      });
    },
    cancel(){
      this.topName = '课间违纪详情';
      if(this.isUpdate){
        this.reload();
        return;
      }
      this.goBack();
    },
    getViolationClassIntervalDetail(){
      if(!this.id){
        this.violationClassIntervalDetail.violationTime = new Date().format("yyyy-MM-dd HH:mm:ss");
        return;
      }
      violationClassIntervalApi.getDetail(this.id).then(res=>{
        console.log("getViolationClassIntervalDetail",res);
        this.violationClassIntervalDetail = res.data;
        let studentNames = this.violationClassIntervalDetail.studentNames;
        this.violationClassIntervalDetail.studentNameList = this.isEmpty(studentNames) ? [] : studentNames.split(",");
      }).catch(err=>{
        console.error("获取违纪详情失败",err);
        uni.showToast({title: "获取违纪详情失败",icon: "error"});
        this.goBack(1000)
      });
    },
	getClassIdAndNames(){
	  teacherClass.getClassIdAndNames().then(res=>{
	    this.handleRes(res).then(data=>{
	      if(data){
	        data = data.map(item=>{
	          return {value: item.id,text:item.name};
	        })
	      }
	      this.classOptions = data;
	    })
	  });
	},
	getStudentList(){
	  let paras = {page: this.queryStudentInfoPage,pageSize: this.queryStudentInfoPageSize,classId:this.violationClassIntervalDetail.classId};
	  student.getFilterStudentPage(paras).then(res=>{
	    this.handleRes(res).then(data=>{
	      this.queryStudentInfos=[...this.queryStudentInfos,...data.list];
	      this.queryStudentInfoTotalPage=data.totalPage;
	    });
	  })
	},
	loadMore(){
	  if(this.queryStudentInfoTotalPage && this.queryStudentInfoPage >= this.queryStudentInfoTotalPage){
	    console.log("所有数据已加载完毕,无需在加载");
	    return;
	  }
	  this.queryStudentInfoPage++;
	  this.getStudentList();
	},
	studentSwitchChange(student,event){
	  student.checked = event.value;
	},
	receiveStudents(){
    this.showLoading();
	  let studentInfos = this.queryStudentInfos.filter(item=>item.checked);
	  if(studentInfos.length < 1){
      this.hideLoading();
      this.toast("请选择违纪学生");
	    return;
	  }
    if(this.isEmpty(this.violationClassIntervalDetail.handleContent)){
      this.hideLoading();
      this.toast("请填写违纪处理情况");
      return;
    }
    let studentIds = studentInfos.map(item=>item.id);
    let callback = ()=>{
      this.getViolationClassIntervalDetail();
      this.hideLoading();
      this.$refs.popups.close();
    };
    let params = {
      id: this.violationClassIntervalDetail.id,
      studentIds: studentIds,
      handleContent: this.violationClassIntervalDetail.handleContent
    };
    violationClassIntervalApi.receiveStudents(params).then(callback).catch(callback);
	},
  }
}
</script>

<style>
	.popup-content {
	  width: 500rpx; /* 或固定宽度，如 300px */
	  margin: 0 auto; /* 水平居中 */
	  padding: 20px;
	}
  .rule-error-text {
    color: #f56c6c;
    font-size: 12px;
    line-height: 1;
    transition: transform 0.3s;
    transform: translateY(-100%);
  }
</style>
